package com.itic.appbase.applications.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.itic.appbase.framework.common.constants.Constants;

import net.sf.json.JSONObject;

public class SystemWebSocketHandler implements WebSocketHandler{
	    private static final Logger logger;
	    //商品过滤字段
	    protected static String[] commonIgnoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note",
	  			"createTime", "orgCode" };

	    private static final ArrayList<WebSocketSession> users;

	    static {
	        users = new ArrayList<>();
	        logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	    }

	    
	    @Override
	    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
	        logger.debug("connect to the websocket success......");
	        users.add(session);
	        String userId = (String) session.getAttributes().get(Constants.WS_USER_NAME);
	       
	        if( null != userId ){
	        	HashMap<String,Object> dataMap = new HashMap<String,Object>();
	        	JSONObject fromObject = JSONObject.fromObject(dataMap);
	        	//发送消息给客户端
	        	TextMessage textMessage = new TextMessage( fromObject.toString() );
	        	sendMessageToUser(userId, textMessage);
	        }
	    }

		@Override
	    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

	        //sendMessageToUsers();
	    }

	    @Override
	    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
	        if(session.isOpen()){
	            session.close();
	        }
	        logger.debug("websocket connection closed......");
	        users.remove(session);
	    }

	    @Override
	    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
	        logger.debug("websocket connection closed......");
	        users.remove(session);
	        String userId = (String) session.getAttributes().get(Constants.WS_USER_NAME);
	        System.out.println(userId);
	    }

	    @Override
	    public boolean supportsPartialMessages() {
	        return false;
	    }

	    /**
	     * 给所有在线用户发送消息
	     *
	     * @param message
	     */
	    public void sendMessageToUsers(TextMessage message) {
	        for (WebSocketSession user : users) {
	            try {
	                if (user.isOpen()) {
	                    user.sendMessage(message);
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }

	    /**
	     * 给某个用户发送消息
	     *
	     * @param userName
	     * @param message
	     */
	    public void sendMessageToUser(String userName, TextMessage message) {
	        for (WebSocketSession user : users) {
	            if (user.getAttributes().get(Constants.WS_USER_NAME).equals(userName)) {
	                try {
	                    if (user.isOpen()) {
	                        user.sendMessage(message);
	                    }
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	                break;
	            }
	        }
	    }
	    
}
